local skel = fk.CreateSkill {
  name = "#ready_skill_trigger",
}


---@class DIYUtility
local DIY = require "packages/diy_utility/_base"



--- 获得蓄势技，增加蓄势小按钮
skel:addEffect(fk.EventAcquireSkill, {
  global = true,
  can_refresh = function (self, event, target, player, data)
    return target == player and data.skill:hasTag(DIY.ReadySkill)
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:handleAddLoseSkills(player, "diy_ready_skill&", nil, false, true)
  end,
})

--- 游戏开始时，增加蓄势小按钮
-- 注意，全局触发技能添加到游戏比角色技能晚，无法检测开局添加的角色技能
skel:addEffect(fk.GamePrepared, {
  global = true,
  can_refresh = function (self, event, target, player, data)
    return not player:hasSkill("diy_ready_skill&", true) and
    table.find(player:getAllSkills(), function (s)
      return s:hasTag(DIY.ReadySkill)
    end)
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:handleAddLoseSkills(player, "diy_ready_skill&", nil, false, true)
  end,
})

-- 失去所有蓄势技后，删除蓄势小按钮
skel:addEffect(fk.EventLoseSkill, {
  global = true,
  can_refresh = function (self, event, target, player, data)
    return target == player and player:hasSkill("diy_ready_skill&", true)
    and data.skill and data.skill:hasTag(DIY.ReadySkill) and
    not table.find(player:getAllSkills(), function (s) return s:hasTag(DIY.ReadySkill) end)
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:handleAddLoseSkills(player, "-diy_ready_skill&", nil, false, true)
  end,
})

-- 洗牌后，重置蓄势
-- 在refresh触发新时机有点危险，但是无所谓了
skel:addEffect(fk.AfterDrawPileShuffle, {
  global = true,
  can_refresh = function (self, event, target, player, data)
    return table.find(player:getAllSkills(), function(s)
      return DIY.isReadying(player, s)
    end)
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    local skills = {}
    for _, s in ipairs(player:getAllSkills()) do
      if DIY.isReadying(player, s) then
        room:setPlayerMark(player, "@diy_skill_readying:::"..s.name, 0)
        table.insert(skills, s)
      end
    end
    for _, s in ipairs(skills) do
      room.logic:trigger(DIY.SkillReadyFinish, player, {
        who = player, skill = s, reason = "shuffle"
      })
    end
  end,
})

-- 发动蓄势技后，令之开始蓄势
skel:addEffect(fk.AfterSkillEffect, {
  global = true,
  can_refresh = function (self, event, target, player, data)
    return target == player and data.skill and data.skill:hasTag(DIY.ReadySkill) and not data.skill.is_delay_effect
    and not DIY.isReadying(player, data.skill)
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    local skill = data.skill
    local skill_name = (skill:getSkeleton() or skill).name
    room:addTableMarkIfNeed(player, "@diy_skill_readying", skill_name)
    room.logic:trigger(DIY.SkillReadyStart, player, {
      who = player, skill = skill, reason = "useskill"
    })
  end,
})


return skel
